package com.elitedatai.mchtest.manage.repository;

import com.elitedatai.mchtest.manage.model.entity.DeviceFirmwareEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface DeviceFirmwareRepository extends JpaRepository<DeviceFirmwareEntity,Integer> {

@Query("SELECT d FROM DeviceFirmwareEntity d JOIN FirmwareModelEntity f ON d.firmwareId = f.firmwareId " +
        "WHERE d.workspaceId = :workspaceId AND d.firmwareVersion = :version AND d.status = true " +
        "AND (:deviceName IS NULL OR :deviceName = '' OR f.deviceName = :deviceName)")
Optional<DeviceFirmwareEntity> findByWorkspaceIdAndFirmwareVersionAndStatusAndDeviceName(
        @Param("workspaceId") String workspaceId,
        @Param("version") String version,
        @Param("deviceName") String deviceName);

    @Query("SELECT d FROM DeviceFirmwareEntity d JOIN FirmwareModelEntity f ON d.firmwareId = f.firmwareId " +
            "WHERE f.deviceName = :deviceName AND d.status = true " +
            "ORDER BY d.releaseDate DESC, d.firmwareVersion DESC")
    Optional<DeviceFirmwareEntity> findFirstByDeviceNameOrderByReleaseDateDescFirmwareVersionDesc(
            @Param("deviceName") String deviceName);

    int countByWorkspaceIdAndFileMd5(String workspaceId, String fileMd5);

    @Query("SELECT d FROM DeviceFirmwareEntity d JOIN FirmwareModelEntity f ON d.firmwareId = f.firmwareId " +
            "WHERE d.workspaceId = :workspaceId " +
            "AND (:status IS NULL OR d.status = :status) " +
            "AND (:productVersion IS NULL OR d.firmwareVersion LIKE %:productVersion%) " +
            "AND (:deviceName IS NULL OR :deviceName = '' OR f.deviceName = :deviceName)")
    Page<DeviceFirmwareEntity> findFirmwarePagination(@Param("workspaceId") String workspaceId,
                                                      @Param("status") Boolean status,
                                                      @Param("productVersion") String productVersion,
                                                      @Param("deviceName") String deviceName,
                                                      Pageable pageable);

    DeviceFirmwareEntity findDeviceFirmwareEntityByFirmwareId(String firmwareId);
}
